package com.ficus.road.maintain.file;

import com.obs.services.ObsClient;
import com.obs.services.model.*;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * @author xiawen yang
 * @date 2022/6/20 下午3:36
 */
@Slf4j
public class OBSFileClient extends AbstractFileClient<OBSClientConfig> {

    private ObsClient obsClient;

    public OBSFileClient(String clientName, OBSClientConfig config) {
        super(clientName, config);
    }

    @Override
    protected void doInit() {
        obsClient = new ObsClient(config.getAccessKeyId(), config.getAccessKeySecret(), config.getEndpoint());
    }

//    @Override
//    public UploadResult upload(byte[] content, String path) throws Exception {
//        return null;
//    }

    @Override
    protected UploadResult upload0(InputStream inputStream, String path, String contentType) {
        UploadResult uploadResult;
        try {
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(contentType);
            obsClient.putObject(config.getBucketName(), path, inputStream, metadata);
            String url = getUrl(path);
            uploadResult = new UploadResult(url, path, 200);
        } catch (Exception e) {
            log.error("obs upload file met exception:", e);
            uploadResult = new UploadResult(null, null, 400);
            return uploadResult;
        }
        return uploadResult;
    }

    @Override
    public void uploadDirect(byte[] content, String path) {
        PutObjectRequest request = new PutObjectRequest(config.getBucketName(), path, new ByteArrayInputStream(content));
        obsClient.putObject(request);
    }

    @Override
    public ObsObject getContent(String path) {
        return obsClient.getObject(config.getBucketName(), path);
    }

    @Override
    public Object getContentByUrl(String url) {
        String str = OBSClientConfig.urlPrefix;
        int beginIndex = url.indexOf(str);
        if (beginIndex == -1)
            return null;
        String path = url.substring(beginIndex + str.length());
        return getContent(path);
    }

    @Override
    public String getUrl(String path) throws Exception {
        TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.GET, OBSClientConfig.FILE_EXPIRATION_TIME);
        request.setBucketName(config.getBucketName());
        request.setObjectKey(path);
        TemporarySignatureResponse response = obsClient.createTemporarySignature(request);
        return response.getSignedUrl();
    }
}
